package com.cz.nongyetongv5.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.BlueLoadingProgress;
import com.cz.nongyetongv5.utils.Conf;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;
import com.loopj.android.http.Base64;

public class YangpinchouyangActivity extends Activity implements
        OnClickListener {

    private WebView wvStart;

    private Button btnLeft;

    private Button btnCenter;

    private Button btnRight;

    private User user;

    private ViewGroup btnBack;

    private BlueLoadingProgress blpLoading = null;

    private TextView tvTitle = null;
    private TextView titleState = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        InitApplication initApplication = (InitApplication) getApplicationContext();

        initApplication.getActivities().add(this);

        setContentView(R.layout.activity_chouyangrenwu);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("抽样列表");
        this.findViewById(R.id.footer).setVisibility(View.GONE);
        titleState = (TextView) findViewById(R.id.titleState);

        wvStart = (WebView) findViewById(R.id.wvStart);

        btnLeft = (Button) findViewById(R.id.btnLeft);

        btnLeft.setBackgroundColor(getResources().getColor(R.color.title_color));


        btnRight = (Button) findViewById(R.id.btnRight);
        btnRight.setText("样品抽样");
        btnCenter = (Button) findViewById(R.id.btnCenter);
        btnCenter.setText("统计汇总");
        btnCenter.setVisibility(View.VISIBLE);
        findViewById(R.id.btnCenterLine).setVisibility(View.VISIBLE);
        btnLeft.setOnClickListener(this);
        btnCenter.setOnClickListener(this);
        btnRight.setOnClickListener(this);
        btnRight.setText("列表显示");
        btnBack = (ViewGroup) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);

        blpLoading = (BlueLoadingProgress) findViewById(R.id.blpLoading);
        blpLoading.setVisibility(View.GONE);

        user = (User) getIntent().getSerializableExtra("user");

        // 存在网络的情况下

        // 启动javascr
        wvStart.getSettings().setJavaScriptEnabled(true);

        wvStart.getSettings().setLoadsImagesAutomatically(true);
        wvStart.addJavascriptInterface(new MobInterp(), "mobinterp");
        wvStart.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                blpLoading.setVisibility(View.VISIBLE);

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                if (blpLoading != null) {

                    blpLoading.stopLoading();
                    blpLoading.setVisibility(View.GONE);

                }
                super.onPageFinished(view, url);
            }
        });
        //


        wvStart.loadUrl(this.getStatUrl());
        btnCenter.setVisibility(View.GONE);
        loadRightTitle();
    }

    /**
     * 加载去主页的按钮
     */
    public void loadRightTitle() {

        ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

        View view = GoHomeUtil.createPopView(this, new String[]{"主页", "去年",
                "今年"});

        // 弹出更多的菜单
        final PopupWindow pop = new PopupWindow(view,
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

        // 需要设置一下此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());

        // 设置点击窗口外边窗口消失
        pop.setOutsideTouchable(true);

        // 设置此参数获得焦点，否则无法点击
        pop.setFocusable(true);

        final Button btn01 = (Button) pop.getContentView().findViewWithTag(
                "btn0");

        final Button btn02 = (Button) pop.getContentView().findViewWithTag(
                "btn1");

        final Button btn03 = (Button) pop.getContentView().findViewWithTag(
                "btn2");

        OnClickListener menuOnClick = new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (v == btn01) {
                    GoHomeUtil.goHome(getApplicationContext());
                }

                if (v == btn02) {

                    GregorianCalendar calendar = new GregorianCalendar();
                    calendar.add(Calendar.YEAR, -1);

                    year = calendar.get(Calendar.YEAR) + "";

                    String url = new ConfigUtil(getResources()).getPreHttpUrl()
                            + getString(R.string.duchaxuncha_count_url)
                            + user.getKnowRegion() + "/year/" + year;

                    //					year="2016";
                    wvStart.loadUrl(getStatUrl());

                }

                if (v == btn03) {
                    String url = new ConfigUtil(getResources()).getPreHttpUrl()
                            + getString(R.string.duchaxuncha_count_url)
                            + user.getKnowRegion();
                    year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
                    wvStart.loadUrl(getStatUrl());
                }

                pop.dismiss();
            }
        };

        btn01.setOnClickListener(menuOnClick);

        btn02.setOnClickListener(menuOnClick);

        btn03.setOnClickListener(menuOnClick);

        btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

        btnMeanMore.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                //            	   ChouyangrenwuActivity.setCheckPlan(null);
                //            	   ChanPinJianCePlanRecordActivity.pid=null;
                //            	   ChanPinJianCeActivity.bjdw=null;
                //            	   Intent intent = new Intent(YangpinchouyangActivity.this,ChanPinJianCeActivity.class);
                //                   // 传递到下一个页面
                //         		  intent.putExtra("user", user);
                //         	       startActivity(intent);
                //
                if (pop.isShowing()) {
                    // 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
                    pop.dismiss();
                } else {
                    // 显示窗口
                    pop.showAsDropDown(v);
                }

            }
        });

    }

    @Override
    protected void onDestroy() {

        InitApplication initApplication = (InitApplication) getApplicationContext();

        initApplication.getActivities().remove(this);

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {

        if (v == btnBack) {

            finish();

            return;
        }

        btnLeft.setBackgroundResource(R.drawable.btn_back_pressed);
        btnCenter.setBackgroundResource(R.drawable.btn_back_pressed);
        btnRight.setBackgroundResource(R.drawable.btn_back_pressed);
        TextView lab = (TextView) this.findViewById(R.id.setting_str);
        lab.setText("更多");

        if (v == btnLeft) {

            lab.setText("新建抽样");
            tvTitle.setText("样品抽样");
            btnLeft.setBackgroundColor(getResources().getColor(R.color.title_color));

            type = "check";
            wvStart.loadUrl(getStatUrl());


        } else if (v == btnCenter) {

            tvTitle.setText("统计汇总");
            lab.setText("更多");
            btnCenter.setBackgroundColor(getResources().getColor(
                    R.color.title_color));

            type = "Stat";
            wvStart.loadUrl(getStatUrl());

        } else if (btnRight == v) {
            lab.setText("更多");
            btnRight.setBackgroundColor(getResources().getColor(
                    R.color.title_color));
            tvTitle.setText("列表显示");
            type = "List";
            wvStart.loadUrl(getStatUrl());
            //            Intent intent = new Intent(this,ChanPinJianCeActivity.class);
            //            intent.putExtra("user", this.user);
            //            startActivity(intent);

        }

    }

    private String type = "list";//check;Stat;List
    private String year =  String.valueOf(Calendar.getInstance().get(Calendar.YEAR));

    private String getUname() {
        try {
            return URLEncoder.encode(URLEncoder.encode(user.getUsername(), "utf-8"), "utf-8");
            // return new String(Base64.encode(user.getUsername().getBytes("utf-8"),Base64.DEFAULT));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user.getUsername();
    }

    private String getUrl(String data) {
        try {
            return URLEncoder.encode(URLEncoder.encode(data, "utf-8"), "utf-8");

            // return new String(Base64.encode(user.getUsername().getBytes("utf-8"),Base64.DEFAULT));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user.getUsername();
    }

    private String getStatUrl() {
        String startTime = year + "-01-01";
        String endTime = year + "-12-31";
        if (type == "check") {
            String url = Conf.v160918_pretask + "tasks.html?user=" + this.getUname() + "&code=" + user.getKnowRegion() + "&c=1&year=" + year;
            Log.d("v16091", url);
            return url;
        }

        String param = "{\"user\":\"" + user.getUsername() + "\",\"year\":" + year + "}";
        String url = Conf.v160918_pretask + "GetSamplingList.html?year=" + year + "&param=" + getUrl(param);
        Log.d("test_url", url);
        return url;

        //	    String url = getString(R.string.planurl);
        //		       url+="/sample"+type+".html?year="+year+"&data={\"begin_date\":\""+startTime
        //       		   +"\",\"region\":\""+user.getKnowRegion()+"\",\"user\":\""+user.getKnowRegion()+"\",\"end_date\":\""+endTime+"\"}";
        //		       Log.d("rafe",url);
        //		       return url;

    }

    public class MobInterp {

        public MobInterp() {

        }

        @JavascriptInterface
        public void toDetail(String type, String pid, String title) {
            Intent intent = new Intent(YangpinchouyangActivity.this, WebDetailActivity.class);
            intent.putExtra("pid", pid);
            ChouyangrenwuActivity.setCheckPlan(pid);
            intent.putExtra("type", "check");
            intent.putExtra("title", "任务详情");
            intent.putExtra("user", user);

            startActivity(intent);
        }

        @JavascriptInterface
        public void toCheck(String type, String pid, String title) {
            Intent intent = new Intent(YangpinchouyangActivity.this, ChanPinJianCeActivity.class);
            // 传递到下一个页面
            intent.putExtra("user", user);
            ChouyangrenwuActivity.setCheckPlan(pid);
            ChanPinJianCePlanRecordActivity.pid = pid;
            startActivity(intent);
        }

        @JavascriptInterface
        public void toSamplingDetail(String pid) {
            Intent intent = new Intent(YangpinchouyangActivity.this, WebDetailActivity.class);
            intent.putExtra("pid", pid);
            intent.putExtra("type", "toSamplingDetail");
            intent.putExtra("title", "抽样详情");
            intent.putExtra("user", user);
            startActivity(intent);
        }


    }
}